<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商超管理</el-breadcrumb-item>
      <el-breadcrumb-item>商超管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="已开启" name="1">
          <el-row :gutter="20" style="position: relative">
            <el-col :span="6">
              <el-input
                v-model="seachlist.name"
                placeholder="商超名称"
                clearable
              >
                <el-button
                  slot="append"
                  @click="getsearchTableList"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-col>
            <!-- <el-col :span="3">
							<el-select v-model="seachlist.status" placeholder="选择状态">
								<el-option value="" label="选择状态"></el-option>
								<el-option key="1" label="开启" value="1"></el-option>
								<el-option key="0" label="关闭" value="0"></el-option>
							  </el-select>
						</el-col> -->
            <!-- <el-button type="primary" @click="getsearchTableList">搜索</el-button> -->
            <!-- <el-button @click="clear">清空</el-button> -->
            <el-button
              style="position: absolute; right: 10px"
              type="primary"
              @click="showAdd"
              >添加商超</el-button
            >
          </el-row>
          <el-table :data="tableList" border stripe>
            <el-table-column
              label="序号"
              prop="sort"
              width="50px"
            ></el-table-column>
            <el-table-column label="商超名称" prop="cmName"></el-table-column>
            <el-table-column label="商超图标">
              <template slot-scope="scope">
                <img :src="scope.row.icon" alt="" class="scope-img" />
              </template>
            </el-table-column>
            <el-table-column
              label="链接"
              prop="h5Url"
              width="300px"
            ></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="statusChanged(scope.row, scope.row.id)"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="数据" align="center">
              <template slot-scope="scope">
                <div @click="goDetail(scope.row.id)" class="tablelist-li-tit">
                  查看数据
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <!-- <el-button @click="showEdit(scope.row.id)" type="primary" size="mini">商超配置</el-button> -->

                <div @click="showEdit(scope.row.id)" class="tablelist-li-tit">
                  商超配置
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageCount"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="已关闭" name="2">
          <el-row :gutter="20" style="position: relative">
            <el-col :span="6">
              <el-input v-model="nameC" placeholder="商超名称" clearable>
                <el-button
                  slot="append"
                  @click="getsearchTableListC"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-col>
            <el-button
              style="position: absolute; right: 10px"
              type="primary"
              @click="showAdd"
              >添加商超</el-button
            >
          </el-row>
          <el-table :data="tableListC" border stripe>
            <el-table-column
              label="序号"
              prop="sort"
              width="50px"
            ></el-table-column>
            <el-table-column label="商超名称" prop="cmName"></el-table-column>
            <el-table-column label="商超图标">
              <template slot-scope="scope">
                <img :src="scope.row.icon" alt="" class="scope-img" />
              </template>
            </el-table-column>
            <el-table-column
              label="链接"
              prop="h5Url"
              width="300px"
            ></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="statusChanged(scope.row, scope.row.id)"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="数据">
              <template slot-scope="scope">
                <el-button
                  @click="goDetail(scope.row.id)"
                  type="primary"
                  size="mini"
                  >查看数据</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEdit(scope.row.id)"
                  type="primary"
                  size="mini"
                  >商超配置</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChangeC"
            @current-change="handleCurrentChangeC"
            :current-page="pageCountC"
            :page-size="pageSizeC"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalC"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog title="添加商超" :visible.sync="addDialogVisible" width="50%">
      <el-form ref="addFormRef" :model="addForm" label-width="120px">
        <el-form-item label="商超名称">
          <el-input v-model="addForm.cmName"></el-input>
        </el-form-item>
        <el-form-item label="商超图标">
          <el-button type="primary" size="mini" @click="chooseImage"
            >点击上传</el-button
          >
          <input
            @change="photoChange($event)"
            type="file"
            id="upload_file"
            multiple
            style="display: none"
          />
          <div v-if="addForm.icon != ''">
            <img
              class="editIcon"
              :src="'data:image/jpeg;base64,' + addForm.icon"
            />
          </div>
        </el-form-item>
        <el-form-item label="跳转地址">
          <el-input v-model="addForm.h5Url"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
        <el-form-item label="营销标签">
          <el-input v-model="addForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="首页展示排序">
          <div class="formitem">
            <el-input v-model="addForm.sort" placeholder="输入排序"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="保存后立即开启">
          <el-radio v-model="addForm.status" label="1">立即开启</el-radio>
          <el-radio v-model="addForm.status" label="0">暂不开启</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSub">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" label-width="120px">
        <el-form-item label="商超名称">
          <el-input v-model="editForm.cmName"></el-input>
        </el-form-item>
        <el-form-item label="商超图标">
          <el-button type="primary" size="mini" @click="chooseImageUpdate"
            >点击上传</el-button
          >
          <input
            @change="photoUpdateChange($event)"
            type="file"
            id="upload_file_update"
            multiple
            style="display: none"
          />
          <div>
            <img
              class="editIcon"
              :src="'data:image/jpeg;base64,' + editForm.icon"
            />
          </div>
        </el-form-item>
        <el-form-item label="跳转地址">
          <el-input v-model="editForm.h5Url"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="营销标签">
          <el-input v-model="editForm.marketLabel"></el-input>
        </el-form-item>
        <el-form-item label="首页展示排序">
            <el-input v-model="editForm.sort" placeholder="输入排序"></el-input>
        </el-form-item>
        <el-form-item label="保存后立即开启">
          <el-radio v-model="editForm.status" label="1">立即开启</el-radio>
          <el-radio v-model="editForm.status" label="0">暂不开启</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableList: [],
      tableListC: [],
      pageCount: 1,
      pageSize: 20,
      total: 0,
      pageCountC: 1,
      pageSizeC: 20,
      totalC: 0,
      addForm: {},
      addDialogVisible: false,
      editForm: {},
      editDialogVisible: false,
      seachlist: { name: "" },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      isFirstEnter: false,

      activeName: "1",
      nameC: "",
      allotChannel: {
        dialogVisible: false,
        sourceChannelData: [],
        targetChannelData: [],
      },
    };
  },
  created() {
    this.getTableList();
    this.getTableListC();
    this.isFirstEnter = true;
  },
  beforeRouteEnter(to, from, next) {
    if (from.path == "/commodityMarketDetail") {
      to.meta.isBack = true;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isBack || this.isFirstEnter) {
      this.pageCount = 1;
      this.pageSize = 20;
      this.pageCountC = 1;
      this.pageSizeC = 20;
      this.activeName = "1";
      this.nameC = "";
      this.total = 0;
      this.totalC = 0;
      this.seachlist = { name: "" };
      this.tableList = [];
      this.tableListC = [];
      this.getTableList();
      this.getTableListC();
    }
    this.$route.meta.isBack = false;
    this.isFirstEnter = false;
  },
  methods: {
    async getTableList() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { data: res } = await this.$http.post("/commodityMarket/list", {
        name: this.seachlist.name,
        status: "1",
        pageCount: this.pageCount,
        pageSize: this.pageSize,
      });
      // console.log(res);
      this.tableList = res.data.records;
      this.total = res.data.total;
      setTimeout(() => {
        loading.close();
      }, 500);
    },
    getsearchTableList() {
      this.pageCount = 1;
      this.getTableList();
    },
    async getTableListC() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { data: res } = await this.$http.post("/commodityMarket/list", {
        name: this.nameC,
        status: "0",
        pageCount: this.pageCountC,
        pageSize: this.pageSizeC,
      });
      setTimeout(() => {
        loading.close();
      }, 500);
      // console.log(res);
      this.tableListC = res.data.records;
      this.totalC = res.data.total;
    },
    getsearchTableListC() {
      this.pageCountC = 1;
      this.getTableListC();
    },
    clear() {
      this.seachlist = { name: "", status: "" };
      this.getTableList();
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getTableList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageCount = val;
      this.getTableList();
    },
    handleSizeChangeC(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSizeC = val;
      this.getTableListC();
    },
    handleCurrentChangeC(val) {
      // console.log(`当前页: ${val}`);
      this.pageCountC = val;
      this.getTableListC();
    },
    showAdd() {
      this.addForm = {
        sort: "",
        cmName: "",
        icon: "",
        h5Url: "alipays://platformapi/startapp?appId=20000067&url=",
        dayInterestRate: "",
        maxAmt: "",
        loanPeople: "",
        fkStartTime: "",
        fkEndTime: "",
        tagVoList: [
          { value: "", code: "" },
          { value: "", code: "" },
        ],
        isHot: "0",
        type: "0",
        status: "0",
        rejectType: "0",
        rejectSort: "",
        loanType: "0",
        androidStatus: "app",
        iosStatus: "app",
        loanSort: "",
        singleAmt: "",
        isLoginShow: "0",
      };
      this.addDialogVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    async addSub() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.addForm.sort == "") {
        this.addForm.sort = "0";
      }
      if (this.addForm.rejectSort == "") {
        this.addForm.rejectSort = "0";
      }
      if (this.addForm.loanSort == "") {
        this.addForm.loanSort = "0";
      }
      if (this.addForm.singleAmt == "" || this.addForm.singleAmt == null) {
        this.addForm.singleAmt = "0";
      }
      const { data: res } = await this.$http.post(
        "/commodityMarket/save",
        this.addForm
      );
      console.log(res);
      setTimeout(() => {
        loading.close();
      }, 500);
      if (res.code !== 200) {
        return this.$message.error(res.msg);
      } else {
        this.$message.success("修改成功");
        this.addDialogVisible = false;
        this.getTableList();
        this.getTableListC();
      }
    },
    async showEdit(id) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { data: res } = await this.$http.post("/commodityMarket/getById", {
        id: id,
      });
      console.log(res);
      setTimeout(() => {
        loading.close();
      }, 500);
      this.editForm = res.data;
      // if(this.editForm.icon!=''){
      var urlBase = "";
      await this.$base64Img(this.editForm.icon).then((res) => {
        //调用全局方法
        urlBase = res;
      });
      this.editForm.icon = urlBase.split(",")[1];
      // }
      this.editDialogVisible = true;
    },
    async editSub() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.editForm.singleAmt == "" || this.editForm.singleAmt == null) {
        this.editForm.singleAmt = "0";
      }
      const { data: res } = await this.$http.post(
        "/commodityMarket/update",
        this.editForm
      );
      setTimeout(() => {
        loading.close();
      }, 500);
      if (res.code !== 200) {
        return this.$message.error(res.msg);
      } else {
        this.$message.success("修改成功");
        this.editDialogVisible = false;
        this.getTableList();
        this.getTableListC();
      }
    },
    // 监听switch状态改变
    async statusChanged(tableList, id) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { data: res } = await this.$http.post("/commodityMarket/updateType", {
        id: id,
        type: tableList.status,
      });
      setTimeout(() => {
        loading.close();
      }, 500);
      this.getTableList();
      this.getTableListC();
      if (res.code !== 200) {
        return this.$message.error("修改状态失败");
      }
      this.$message.success("修改状态成功");
    },
    goDetail(id) {
      this.$router.push({ path: "/commodityMarketDetail", query: { id: id } });
    },
    chooseImage() {
      document.getElementById("upload_file").click(); //触发input-file文件上传控件 事件photoChange
    },
    async photoChange(el) {
      var file = el.target.files[0]; //name: "dangqi1.png" || type: "image/png"
      var type = file.type.split("/")[0];
      if (type === "image") {
        var dataURL = await this.toBase64(file);
        this.addForm.icon = dataURL.split(",")[1];
      } else {
        alert("上传了非图片");
      }
    },
    chooseImageUpdate() {
      document.getElementById("upload_file_update").click(); //触发input-file文件上传控件 事件photoChange
    },
    async photoUpdateChange(el) {
      var file = el.target.files[0]; //name: "dangqi1.png" || type: "image/png"
      var type = file.type.split("/")[0];
      if (type === "image") {
        var dataURL = await this.toBase64(file);
        this.editForm.icon = dataURL.split(",")[1];
      } else {
        alert("上传了非图片");
      }
    },
    toBase64(file) {
      return new Promise(function (resolve, reject) {
        //将图片img转化为base64
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function () {
          resolve(reader.result);
        };
      });
    },
    handleClick() {
      // console.log(this.activeName);
    },
  },
};
</script>

<style lang="less" scoped>
.tablelist-li-tit {
  font-size: 12px;
  color: #3878ea;
  margin-bottom: 4px;
  cursor: pointer;
}
.scope-img {
  height: 50px;
  width: 50px;
}
.el-icon-success {
  font-size: 26px;
  color: green;
}
.el-icon-error {
  font-size: 26px;
  color: #d60404;
}
.formitem {
  display: flex;
  align-items: center;
}
.el-form-item {
  margin-bottom: 10px;
}
.inp-1 {
  width: 30%;
  margin-right: 10px;
}
.inp-2 {
  width: 20%;
}
.editIcon {
  width: 80px;
  height: 80px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.el-transfer-panel__filter .el-input__icon {
  margin-left: 15px;
}
</style>
